package cqgans.app.sunao.com.cqgans.ui;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import cqgans.app.sunao.com.cqgans.adapter.RankAdapter;
import cqgans.app.sunao.com.cqgans.bean.PageResult;
import cqgans.app.sunao.com.cqgans.bean.RankInfo;
import cqgans.app.sunao.com.cqgans.common.AppConstant;
import cqgans.app.sunao.com.cqgans.widget.LoadingDialog;
import cqgans.app.sunao.com.cqgansnew.R;

import static cqgans.app.sunao.com.cqgans.common.AppConstant.user;

@ContentView(R.layout.activity_rank)
public class RankActivity extends BaseActivity {

    @ViewInject(R.id.tab_layout)
    private TabLayout tabLayout;

    @ViewInject(R.id.view_pager)
    private ViewPager viewPager;

    @ViewInject(R.id.user_no_et)
    private EditText userNoEt;

    @ViewInject(R.id.user_name_et)
    private EditText userNameEt;

    @ViewInject(R.id.user_rank_info)
    private TextView userRankTv;

    private LoadingDialog progressDialog;

    private int page = 1, count = 20;

    String[] tabs = new String[]{"日", "周", "月", "年", "总"};

    PageResult<RankInfo> pageResult;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        init();
    }


    private void init() {
        pageResult = new PageResult<>();
        progressDialog = new LoadingDialog(this, "数据加载中，请稍侯...");
        viewPager.setAdapter(new MyPagerAdapter());
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabLayout.getTabCount(); i ++) {
            tabLayout.getTabAt(i).setText(tabs[i]);
        }
        findViewById(R.id.search_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageResult.currentPage = 1;
                pageResult.pageResults.clear();
                search();
            }
        });
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.clear_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userNameEt.setText("");
                userNoEt.setText("");
            }
        });
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                pageResult.currentPage = 1;
                pageResult.pageResults.clear();
                search();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        search();
    }


    private void loadData(int rankType) {
        RequestParams params = new RequestParams(AppConstant.URL + AppConstant.RANK_URL);
        progressDialog = new LoadingDialog(this, "加载中...");
        progressDialog.show();
        JSONObject mjson = new JSONObject();
        try {
            mjson.put("loginUserNo", user.getMobile());
            if(!TextUtils.isEmpty(userNoEt.getText().toString().trim()))
                mjson.put("staffNo", userNoEt.getText().toString().trim());
            if(!TextUtils.isEmpty(userNameEt.getText().toString().trim()))
                mjson.put("staffName", userNameEt.getText().toString().trim());
            mjson.put("rankType", rankType);
            mjson.put("page", pageResult.currentPage);
            mjson.put("count", count);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.setAsJsonContent(true);
        params.setBodyContent(mjson.toString());
        params.addHeader("Content-Type", "application/json");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @SuppressWarnings("WrongConstant")
            @Override
            public void onSuccess(String result) {
                LogUtil.i(result);
                progressDialog.close();
                try {
                    JSONObject resultJson = new JSONObject(result);
                    LogUtil.i(resultJson.toString());
                    if (resultJson.has("flag") && resultJson.getBoolean("flag")) {
                        Gson gson = new Gson();
                        if(resultJson.has("currentUserInfo") && null != resultJson.get("currentUserInfo")) {
                            RankInfo rankInfo = gson.fromJson(resultJson.get("currentUserInfo").toString(), RankInfo.class);
                            String s = "日";
                            if(viewPager.getCurrentItem() == 4) {
                                userRankTv.setText("您的总销售额" + rankInfo.totalSales + "元,排在第" + rankInfo.rank + "名");
                            } else {
                                userRankTv.setText("您本" + tabs[viewPager.getCurrentItem()] + "销售额" + rankInfo.totalSales + "元,排在第" + rankInfo.rank + "名");
                            }
                        }
                        if (resultJson.has("data") && null != resultJson.get("data")
                                && resultJson.getJSONObject("data").has("page")
                                && null != resultJson.getJSONObject("data").get("page")) {
                            PageResult<RankInfo> pr = gson.fromJson(resultJson.getJSONObject("data").get("page").toString(), new TypeToken<PageResult<RankInfo> >(){}.getType());
                            pageResult.currentPage = pr.currentPage;
                            pageResult.totalPage = pr.totalPage;
                            pageResult.countOfCurrentPage = pr.countOfCurrentPage;
                            pageResult.totalCount = pr.totalCount;
                            pageResult.pageResults.addAll(pr.pageResults);
                            setData(pageResult.pageResults);
                        } else {
                            loadFailed();
                            Toast.makeText(RankActivity.this, "请求错误,请稍后再试", 1000).show();
                        }
                    } else {
                        if(resultJson.has("msg")) {
                            Toast.makeText(RankActivity.this, resultJson.getString("msg"), 1000).show();
                        } else {
                            Toast.makeText(RankActivity.this, "请求错误,请稍后再试", 1000).show();
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    loadFailed();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.close();
                LogUtil.e(ex.getMessage());
                Toast.makeText(RankActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
                loadFailed();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.close();
                loadFailed();
            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void search() {
        int type = 0;
        if(viewPager.getCurrentItem() == 0) {
            type = 1;
        } else if(viewPager.getCurrentItem() == 1) {
            type = 2;
        } else if(viewPager.getCurrentItem() == 2) {
            type = 3;
        } else if(viewPager.getCurrentItem() == 3) {
            type = 4;
        } else{
            type = 0;
        }
        loadData(type);
    }

    private void loadFailed() {
        View v = viewPager.findViewWithTag(viewPager.getCurrentItem());
        RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.recycler);
        SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.refresh_layout);
        RankAdapter adapter = (RankAdapter) recyclerView.getAdapter();
        if(null != adapter) {
            adapter.loadMoreComplete();
        }
        refreshLayout.setRefreshing(false);
    }

    private void setData(List<RankInfo> rankInfos) {
        View v = viewPager.findViewWithTag(viewPager.getCurrentItem());
        RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.recycler);
        SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.refresh_layout);
        refreshLayout.setRefreshing(false);
        RankAdapter adapter = (RankAdapter) recyclerView.getAdapter();
        if(null == adapter) {
            adapter = new RankAdapter(rankInfos);
            adapter.bindToRecyclerView(recyclerView);
            adapter.setEmptyView(R.layout.item_empty);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.setNewData(rankInfos);
        }
        if(pageResult.totalPage == pageResult.currentPage) {
            adapter.loadMoreEnd(false);
        }
//        recyclerView.scrollToPosition(rankInfos.size() - 1);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                pageResult.currentPage ++;
                search();
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageResult.currentPage = 1;
                pageResult.pageResults.clear();
                search();
            }
        });
    }

    class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return 5;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View v = getLayoutInflater().inflate(R.layout.item_rank_pager, null);
            RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.recycler);
            recyclerView.setLayoutManager(new LinearLayoutManager(RankActivity.this));
            container.addView(v);
            v.setTag(position);
            return v;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View)object);
        }
    }
}
